package com.feixiang.springbootinit.strategy;
import cn.hutool.json.JSONUtil;
import com.feixiang.springbootinit.common.ErrorCode;
import com.feixiang.springbootinit.exception.BusinessException;
import com.feixiang.springbootinit.model.entity.wechat.QwMessage;
import com.feixiang.springbootinit.model.entity.wechat.QwRecallMessage;
import com.feixiang.springbootinit.model.entity.wechat.QwVideoMessage;
import com.feixiang.springbootinit.model.enums.SessionArchiveMsgTypeEnum;
import com.feixiang.springbootinit.model.vo.wechat.MsgVO;
import com.feixiang.springbootinit.processor.SessionArchiveBatchProcessor;
import com.feixiang.springbootinit.processor.SessionArchiveProcessor;
import com.feixiang.springbootinit.service.QwRecallMessageService;
import com.feixiang.springbootinit.utils.BatchSaveUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
/**
 * 撤回消息处理策略
 */
public class RecallMessageStrategy implements MessageProcessingStrategy {

    @Autowired
    private QwRecallMessageService recallMessageService;

    @Override
    public boolean supports(SessionArchiveMsgTypeEnum msgType) {
        return SessionArchiveMsgTypeEnum.REVOKE == msgType;
    }
    @Override
    public void process(MsgVO msgVO, QwMessage baseMessage) {
        log.info("处理撤回消息");
       try {
           QwRecallMessage recallMessage = new QwRecallMessage();
           recallMessage.setMsgId(msgVO.getMsgid());
           recallMessage.setRecallMsgId(msgVO.getRevoke().getPre_msgid());
           recallMessage.setCreatedTime(new Date());
           recallMessageService.save(recallMessage);
           log.info("保存撤回消息成功,消息id:{}", recallMessage.getMsgId());
        } catch (Exception e) {
            log.error("处理撤回消息失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "处理撤回消息失败");
        }
    }

    /**
     * 批量处理撤回消息
     * @param baseMessages
     */
    @Override
    public void batchProcess(List<QwMessage> baseMessages) {
        if (baseMessages.isEmpty()) {
            log.info("批量处理撤回消息: 空列表，无需处理");
            return;
        }
        log.info("开始批量处理撤回消息，数量: {}", baseMessages.size());
        long sdk = SessionArchiveBatchProcessor.getGlobalSdkInstance();
        List<QwRecallMessage> recallMessages = new ArrayList<>(baseMessages.size());
        for (QwMessage baseMsg : baseMessages) {
            try {
                // 从基础消息中解析出原始消息对象
                MsgVO msgVO = JSONUtil.toBean(baseMsg.getContent(), MsgVO.class);
                if (msgVO.getRevoke() == null) {
                    log.warn("撤回消息内容为空，msgId: {}", baseMsg.getMsgId());
                    continue;
                }
                // 构建撤回消息实体
                QwRecallMessage recallMsg = new QwRecallMessage();
                recallMsg.setMsgId(msgVO.getMsgid());
                recallMsg.setRecallMsgId(msgVO.getRevoke().getPre_msgid());
                recallMsg.setCreatedTime(new Date());
                recallMessages.add(recallMsg);
            } catch (Exception e) {
                log.error("批量处理单条撤回消息失败, msgId: {}", baseMsg.getMsgId(), e);
                // 单条失败不影响整体批次，继续处理其他消息
            }
        }
        // 批量保存到数据库
        BatchSaveUtil.batchSave(recallMessages, recallMessageService::insertBatch, "撤回消息");
//        if (!recallMessages.isEmpty()) {
//            try {
//                // 分批次保存，每批最多500条
//                int batchSize = 500;
//                for (int i = 0; i < recallMessages.size(); i += batchSize) {
//                    int end = Math.min(i + batchSize, recallMessages.size());
//                    List<QwRecallMessage> subList = recallMessages.subList(i, end);
//                    recallMessageService.saveBatch(subList);
//                }
//                log.info("成功保存 {} 条撤回消息", recallMessages.size());
//            } catch (Exception e) {
//                log.error("批量保存撤回消息失败", e);
//            }
//        }
    }
}
